package com.example.student.controller;

import com.example.student.common.Result;
import com.example.student.entity.SysUser;
import com.example.student.model.PageResult;
import com.example.student.model.UserVO;
import com.example.student.model.PasswordUpdateDTO;
import com.example.student.service.UserService;
import com.example.student.mapper.SysMenuMapper;
import com.example.student.util.SecurityUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Resource
    private UserService userService;
    
    @Resource
    private SysMenuMapper menuMapper;

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentUser() {
        UserVO userInfo = userService.getCurrentUser();
        
        // 获取用户权限列表
        List<String> permissions = new ArrayList<>();
        Long userId = SecurityUtil.getUserId();
        if (userId != null) {
            // 直接从数据库获取用户权限
            permissions = menuMapper.selectPermissionsByUserId(userId);
            System.out.println("用户权限: " + permissions);
        }
        
        // 构造返回结果
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("id", userInfo.getId());
        result.put("username", userInfo.getUsername());
        result.put("realName", userInfo.getRealName());
        result.put("phone", userInfo.getPhone());
        result.put("email", userInfo.getEmail());
        result.put("status", userInfo.getStatus());
        result.put("roles", userInfo.getRoles());
        result.put("roleIds", userInfo.getRoleIds());
        result.put("lastLoginTime", userInfo.getLastLoginTime());
        result.put("avatar", userInfo.getAvatar());
        result.put("permissions", permissions);
        
        return Result.success(result);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        SecurityContextHolder.clearContext();
        return Result.success();
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<Void> updateUserInfo(@Valid @RequestBody SysUser user) {
        userService.updateUserInfo(user);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<Void> changePassword(@Valid @RequestBody PasswordUpdateDTO passwordUpdateDTO) {
        userService.changePassword(passwordUpdateDTO);
        return Result.success();
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:user:list')")
    public Result<PageResult<UserVO>> list(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "realName", required = false) String realName,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return Result.success(userService.getUserList(username, realName, status, pageNum, pageSize));
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:list')")
    public Result<UserVO> getById(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    /**
     * 添加用户
     */
    @PostMapping
    @PreAuthorize("hasAuthority('system:user:add')")
    public Result<Void> add(@Valid @RequestBody SysUser user) {
        userService.addUser(user);
        return Result.success();
    }

    /**
     * 更新用户
     */
    @PutMapping
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result<Void> update(@Valid @RequestBody SysUser user) {
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result<Void> resetPassword(@PathVariable Long id) {
        userService.resetPassword(id);
        return Result.success();
    }

    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestBody SysUser user) {
        userService.updateStatus(id, user.getStatus());
        return Result.success();
    }
    
    /**
     * 分配角色给用户
     */
    @PutMapping("/{id}/roles")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result<Void> assignRoles(@PathVariable Long id, @RequestBody Map<String, List<Long>> roleMap) {
        List<Long> roleIds = roleMap.get("roleIds");
        if (roleIds == null) {
            roleIds = new ArrayList<>();
        }
        userService.assignRoles(id, roleIds);
        return Result.success();
    }
} 